package webfilter.application.authorityctrl;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //响应中文乱码问题, 转码
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String btnValue = req.getParameter("button");
        String userName = req.getParameter("username");
        if (userName == null) {
            req.getSession().setAttribute("msg", "username为空");
            resp.sendRedirect(req.getContextPath() + "/loginAuthority.jsp");
            return;
        }
        //伪数据库username.properties的路径
        String databasePath = req.getServletContext().getRealPath("/WEB-INF/classes/username.properties");
        BufferedReader in = new BufferedReader(new FileReader(databasePath));
        String usernameRead;
        boolean isUserRegistered = false;
        while ((usernameRead = in.readLine()) != null) {
            if (usernameRead.equals(userName)) {
                isUserRegistered = true;
                break;
            }
        }
        in.close();
        
        //请求中文乱码问题, 转码
        btnValue = new String(btnValue.getBytes("iso-8859-1"), "utf-8");
        if (btnValue.equals("登录")) {
            if (isUserRegistered == false) {
                req.getSession().setAttribute("msg", "用户未注册过");
                resp.sendRedirect(req.getContextPath() + "/loginAuthority.jsp");
                return;
            }
            //用户名含有shuoGG的就是管理员
            if (userName.contains("shuoGG")) {
                req.getSession().setAttribute("admin", userName);
            } else {
                req.getSession().setAttribute("user", userName);
            }

        } else if (btnValue.equals("注册")) {
            if (isUserRegistered == true) {
                req.getSession().setAttribute("msg", "用户已经注册过了");
                resp.sendRedirect(req.getContextPath() + "/loginAuthority.jsp");
                return;
            }
            //printWriter的构造函数没有boolean append, 所以只能装饰FileWriter
            PrintWriter pw = new PrintWriter(new FileWriter(databasePath, true));
            pw.println(userName); //append方法实质上还是没有添加的功能
            pw.close();
        } else {
            req.getSession().setAttribute("msg", "你究竟点了什么按钮");
            resp.sendRedirect(req.getContextPath() + "/loginAuthority.jsp");
        }
    }

}
